import { defineStore } from 'pinia';
import type { LoginModalState, LoginModalActions } from '@/types/login';
import { requestQueue } from '@/utils/requestQueue';
import axiosInstance from '@/utils/axios.config';

export const useLoginModalStore = defineStore('loginModal', {
  state: (): LoginModalState => ({
    visible: false,
    loading: false,
    callback: undefined,
  }),

  actions: {
    /**
     * 显示登录弹窗
     * @param callback 登录成功后的回调函数
     */
    showModal(callback?: (success: boolean) => void) {
      this.visible = true;
      this.callback = callback;
    },

    /**
     * 隐藏登录弹窗
     */
    hideModal() {
      this.visible = false;
      this.callback = undefined;
    },

    /**
     * 设置加载状态
     * @param loading 是否加载中
     */
    setLoading(loading: boolean) {
      this.loading = loading;
    },

    /**
     * 处理登录成功
     */
    async handleLoginSuccess() {
      console.log('登录成功，开始处理重试...');
      if (this.callback) {
        this.callback(true);
      }
      this.hideModal();
      // 检查队列中是否有请求
      const queueLength = requestQueue.getQueueLength();
      console.log('重试队列长度:', queueLength);

      if (queueLength > 0) {
        // 重试队列中的请求
        try {
          await requestQueue.retryAllRequests(axiosInstance);
          console.log('所有请求重试完成');
        } catch (error) {
          console.error('请求重试过程中出现错误:', error);
        }
      } else {
        console.log('重试队列为空，无需重试');
      }
    },

    /**
     * 处理登录失败
     */
    handleLoginFailure() {
      if (this.callback) {
        this.callback(false);
      }
    },
  },
});
